package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.jmp.api.dto.TicketOrderSaveRequest;
import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.feign.TicketFeign;
import com.jmp.service.api.admin.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.CompanyDto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageRequest;
import one.stand.dto.PageResponse2;
import one.stand.model.Company;
import one.stand.model.ResultModel;
import one.stand.service.CompanyBaseService;
import one.stand.util.AssertUtil;
import one.stand.util.MoneyUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api("奖券管理")
@RestController
@RequestMapping("/ticket")
public class TicketController {
    public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Autowired
    private TicketFeign ticketFeign;

    @Autowired
    private CompanyBaseService companyBaseService;

    @ApiOperation("首页")
    @GetMapping
    @SecurityAuthCheck
    public ResultModel<TicketIndexResponse> index() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        ResultModel<TicketOrderCountVo> resultModel = ticketFeign.orderCount(TicketOrderCountDto.builder().userId(optUser.getUserId()).build());
        AssertUtil.isTrue(resultModel);
        TicketOrderCountVo vo = resultModel.getData();
        TicketIndexResponse response = TicketIndexResponse.builder()
                .orderCount(vo.getOrderCount())
                .title("已通过：" + vo.getAgreeCount() + "  审核中：" + vo.getAuditingCount() + " 未通过：" + vo.getRefuseCount())
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("我的订单-列表")
    @PostMapping("order/list")
    @SecurityAuthCheck
    public ResultModel<TicketOrderListResponse> orderList(@RequestAttribute PageRequest request) {

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        TicketOrderListDto dto = TicketOrderListDto.builder()
                .userId(optUser.getUserId())
                .build();
        dto.setPageInit(request.getPageNum(), request.getPageSize());
        ResultModel<TicketOrderListVo> resultModel = ticketFeign.orderList(dto);
        AssertUtil.isTrue(resultModel);
        PageResponse2<TicketOrderListResponse.Order> page = ConvertUtils.page2(resultModel.getData().getPage(), order -> {
            Company company = companyBaseService.getById(order.getFromCompanyId());
            return TicketOrderListResponse.Order.builder()
                    .id(order.getId())
                    .fromCompanyName(company.getCompanyName())
                    .orderNo(order.getOrderNo())
                    .orderMoney(MoneyUtil.getMoneyStr(order.getOrderMoney()))
                    .ctime(DATE_FORMAT.format(order.getCtime()))
                    .fileUpload("已上传")
                    .status(order.getStatus() == 2 ? order.getMemo() : (order.getStatus() == 1 ? "已通过审核" : "订单审核中"))
                    .statusType(order.getStatus())
                    .build();
        });

        TicketOrderListResponse response = TicketOrderListResponse.builder()
                .orders(page)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("我的订单-企业列表")
    @PostMapping("order/company/list")
    @SecurityAuthCheck
    public ResultModel<TicketOrderCompanyListResponse> orderList(@RequestAttribute TicketOrderCompanyListRequest request) {
        PageHelper.startPage(1, 20);
        List<CompanyDto> list = companyBaseService.selectTicketCompanyList(request.getKeyword());
        List<TicketOrderCompanyListResponse.Company> page = ConvertUtils.list(list, companyDto -> {
            return TicketOrderCompanyListResponse.Company.builder()
                    .companyId(companyDto.getCompanyId())
                    .companyName(companyDto.getCompanyName())
                    .build();
        });

        TicketOrderCompanyListResponse response = TicketOrderCompanyListResponse.builder()
                .companies(page)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("我的订单-详情")
    @PostMapping("order/info")
    @SecurityAuthCheck
    public ResultModel<TicketOrderInfoResponse> orderInfo(@RequestAttribute TicketOrderInfoRequest request) {
        ResultModel<TicketOrderInfoVo> resultModel = ticketFeign.orderInfo(TicketOrderInfoDto.builder().orderId(request.getOrderId()).build());
        AssertUtil.isTrue(resultModel);
        TicketOrderInfoVo orderInfoDto = resultModel.getData();

        Company company = companyBaseService.getById(orderInfoDto.getFromCompanyId());
        TicketOrderInfoResponse response = TicketOrderInfoResponse.builder()
                .id(orderInfoDto.getId())
                .fromCompanyId(orderInfoDto.getFromCompanyId())
                .fromCompanyName(company.getCompanyName())
                .orderNo(orderInfoDto.getOrderNo())
                .orderMoney(orderInfoDto.getOrderMoney())
                .photo(orderInfoDto.getPhoto())
                .payPhoto(orderInfoDto.getPayPhoto())
                .status(orderInfoDto.getStatus())
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("我的订单-上传或修改订单")
    @PostMapping("order/save")
    @SecurityAuthCheck
    public ResultModel orderSave(@RequestAttribute TicketOrderSaveRequest request) {

        AssertUtil.nonNull(request.getPhoto(), ResultEnum.PARAM_CHECK, "核销票为空");
        AssertUtil.nonNull(request.getOrderNo(), ResultEnum.PARAM_CHECK, "校验编号不能为空");
        AssertUtil.isTrue(Objects.nonNull(request.getOrderMoney()) && request.getOrderMoney().compareTo(BigDecimal.ZERO) > 0, ResultEnum.PARAM_CHECK, "进货金额不能为空且必须大于零");

//        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
//        int count = ticketApiJxsMapper.selectJxs(user.getCompanyId(), "经销商花园购");
//        AssertUtil.isTrue(count > 0, ResultEnum.PARAM_CHECK, "非花园购经销商，无法提交订单！如有疑问请联系：0579-86669669");

        com.jmp.service.api.admin.dto.TicketOrderSaveRequest saveRequest = com.jmp.service.api.admin.dto.TicketOrderSaveRequest.builder()
                .id(request.getOrderId())
                .fromCompanyId(request.getFromCompanyId())
                .orderMoney(request.getOrderMoney())
                .orderNo(request.getOrderNo())
                .photo(request.getPhoto())
                .payPhoto(request.getPayPhoto())
                .build();
        ResultModel resultModel = ticketFeign.orderSave(saveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("我的兑奖码")
    @PostMapping("qr")
    @SecurityAuthCheck
    public ResultModel<TicketQrResponse> qr() {

        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();

        ResultModel<TicketInfoQrResponse> qrResponseResultModel = ticketFeign.infoQr(TicketInfoQrRequest.builder().userId(user.getUserId()).build());
        AssertUtil.isTrue(qrResponseResultModel);
        TicketInfoQrResponse qrResponse = qrResponseResultModel.getData();

        Date now = new Date();
        int status;
        String memo;
        if (qrResponse.getStartTime().after(now)) {
            status = 0;
            memo = "提示：抽奖订单上传截至日期为：2020年9月9日中午12点，现场抽奖时间为：2020年9月10日上午9点（本次活动最终解释权归花园红木家具城）";
        } else if (qrResponse.getStartTime().before(now) && qrResponse.getEndTime().after(now) && qrResponse.getStatus() == 0) {
            status = 1;
            memo = "提示：抽奖活动已开始，请及时至花园红木展销会活动现场兑换抽奖券，过期奖券将自动作废，兑换奖券时向工作人员出示本二维码即可，二维码" + qrResponse.getQrTimes() + "秒会自动刷新。";
        } else if (qrResponse.getStatus() == 1) {
            status = 2;
            memo = "提示：您的奖券已成功兑换，请在有效期内及时使用，过期未使用奖券将作废，无法参加抽奖活动！";
        } else {
            status = 3;
            memo = "感恩有你！2020中国·花园红木家具展销会已圆满结束，期待来年我们再次相会。";
        }

        TicketQrResponse response = TicketQrResponse.builder()
                .status(status)
                .startTime(qrResponse.getStartTime().getTime() - now.getTime())
                .memo(memo)
                .orderMoney(MoneyUtil.getMoneyStr(qrResponse.getOrderMoney()))
                .ticketCount(qrResponse.getNum())
                .qrCode(qrResponse.getQrCode())
                .qrTime(qrResponse.getQrTimes())
                .build();
        return ResultModel.success(response);
    }
}
